import fix_path
import webapp2
import datetime,random
import mailchimp
from google.appengine.ext import db
from google.appengine.datastore.datastore_v4_pb import GqlQuery
from google.appengine.ext.ndb.tasklets import sleep

class dal_select(webapp2.RequestHandler):
    def post(self):
        if self.request.get("user_score"):
            user_result = self.request.get("user_result")
            game = self.request.get("type")
            i=0
            while (db.is_in_transaction() or i>10):
                sleep(0.5)
                i+=1
                
            crowdsum = CrowdSum.get_by_key_name(key_names=game)
            if (crowdsum):
                average=crowdsum.sum/crowdsum.count
                user_result_distance=abs(crowdsum.correctanswer-int(user_result))
                if (user_result_distance != 0):
                    query =  Result.gql("WHERE game = :game AND distance > :user_distance",game=game,user_distance=user_result_distance)
                    better=int(float(query.count())/crowdsum.count*100)
                else:
                    better=100
                self.response.write(str(average)+"#"+str(better))
                
    def get(self):
        if self.request.get("password") == "secretPass":       
            user_result = self.request.get("user_result")
            game = self.request.get("type")
            i=0
            while (db.is_in_transaction() or i>10):
                sleep(0.5)
                i+=1
                
            crowdsum = CrowdSum.get_by_key_name(key_names=game)
            if (crowdsum):
                self.response.write("sum: %s, count: %s <BR/>"%(crowdsum.sum,crowdsum.count))
                average=crowdsum.sum/crowdsum.count
                user_result_distance=abs(crowdsum.correctanswer-int(user_result))
                self.response.write("user distance: %s<BR/>"%(user_result_distance))
                query =  Result.gql("WHERE game = :game AND distance > :user_distance",game=game,user_distance=user_result_distance)
                self.response.write("query count: %s<BR/>"%(float(query.count())/crowdsum.count*100))
                
class dal_insert(webapp2.RequestHandler):
    # correctAnswers holds a dict of the real answers
    correctAnswers = {"wheel":60,"pie":35,"beer":1300} 
    m=None
    
    def get(self):
        if self.request.get("subscribe"):
            email = self.request.get("email")
            subscriber = Subscriber(email=email)
            subscriber.put()
        if self.request.get("filldb") and self.request.get("password") == "secretPass":
            for i in range(100):
                for game in ["pie","wheel","beer"]:
                    result=random.randint(1,1000)
                    resultObj = Result(game=game,result=result,distance=abs(result-self.correctAnswers.get(game)))
                    resultObj.put()
                    crowdsum = CrowdSum.get_or_insert(key_name=game,correctanswer=self.correctAnswers.get(game))
                    crowdsum.sum += result
                    crowdsum.count += 1
                    crowdsum.put()
            
    def post(self):
        # TODO: change to post requests
        if self.request.get("new_session"):
            # create Session object with date, and return it's id in the response
            session = Session(logontime=datetime.datetime.now())
            session.put()
            self.response.write(session.key().id())
            
        elif self.request.get("click"):
            # create Click object with date, source id, and set a session as parent 
            source=self.request.get("source")
            user_id=self.request.get("id")
            session_k = Session.get_by_id(ids=int(user_id)) 
            click = Click(clicktime=datetime.datetime.now() , source=source , parent=session_k)
            click.put()
            
        elif self.request.get("subscribe"):
            email = self.request.get("email")
            subscriber = Subscriber(email=email)
            subscriber.put()
            try:
                if not self.m: 
                    self.m = mailchimp.Mailchimp("14b7af846297a3118de74961ca680275-us3")
                self.m.lists.subscribe("2e87047a35", {"email":email})
            except:
                self.response.write("error")
                               
              
        elif self.request.get("submit"):
            game = self.request.get("type")
            result = int(self.request.get("result"))
            correct_answer=self.request.get("correct_answer")
            #if (game in ["pie","wheel","beer"]):
            
            # put into result object
            resultObj = Result(game=game,result=result,distance=abs(result - int(correct_answer)))
            resultObj.put()
            # and put into CrowdSum object
            crowdsum = CrowdSum.get_or_insert(key_name=game,correctanswer=abs(int(correct_answer)))
            #crowdsum = CrowdSum.get_or_insert(key_name=game,correctanswer=self.correctAnswers.get(game))
            crowdsum.sum += result
            crowdsum.count += 1
            crowdsum.put()     

class CrowdSum(db.Model):
    correctanswer = db.IntegerProperty(required=True)
    sum = db.IntegerProperty(default=0,required=True)
    count = db.IntegerProperty(default=0,required=True)

class Result(db.Model):
    result= db.IntegerProperty(required=True)
    game= db.StringProperty(required=True)
    distance = db.IntegerProperty(required=True)
            
class Session(db.Model):
    logontime = db.DateTimeProperty(required=True)
    name = db.StringProperty()
  
class Click(db.Model):
    clicktime = db.DateTimeProperty(required=True)
    source = db.StringProperty()

class Subscriber(db.Model):
    email = db.StringProperty(required=True)
    
application = webapp2.WSGIApplication([
    ('/db_select', dal_select),
    ('/db_insert', dal_insert)
], debug=True)
